--
-- Author: mm
-- Date: 2018-06-15 11:31:42
--
-- ClassRef
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

ClassRef.EVENT_REFRESH_BAG = "EVENT_REFRESH_BAG"

function ClassRef:ctor(data)
    self.super.ctor(self, data)
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()
end

function ClassRef:init()
    self.curEquipUid = 0
    self.itemChangeHandler = UD:onChanged("bag", handler(self, self.refreshRedPoint))
    self.equipHandler = UD:onChanged("equip",handler(self, self.refreshRedPoint))
    self.playerHandler = UD.player:onChanged(function(name,old,new)
        if name=="level" then
            self:refreshRedPoint()
        end
    end)
    -- UD.player:unChanged(self.playerHandler)
end

function ClassRef:resetJewelsNewFlag()
    self:removeAllItemNewFlag()
    if UD.badge:setNum(Constant.FUNC_TYPE_JEWEL,0) then
	   -- UD.dirty = true
    end
end

function ClassRef:removeAllItemNewFlag()
    for _,v in pairs(UD:getJewels()) do
        v:setIsNewGet(false)
    end
end

function ClassRef:getAllJewels()
    local data = {}
    for _,v in pairs(UD:getJewels()) do
        local j=clone(v)
        j:setOrderLevel(3)
        j:setState(Enums.JewelState.inBag)
        table.insert(data,j)
    end
    for k,v in pairs(UD.equips) do
        if v.jewelSlots then
            for k1,v1 in pairs(v.jewelSlots) do
                if v1.jewel then
                    local j=clone(v1.jewel)
                    j:setEquipTid(v.tid)
                    j:setEquipUid(v.uid)
                    j:setOrderLevel(1)
                    j:setState(Enums.JewelState.inSlot)
                    table.insert(data,j)
                end
            end
        end
        if v.lockedJewelSlot and v.lockedJewelSlot.jewel then
            if v.lockedJewelSlot.jewel then
                local j=clone(v.lockedJewelSlot.jewel)
                j:setEquipTid(v.tid)
                j:setEquipUid(v.uid)
                j:setOrderLevel(1)
                j:setState(Enums.JewelState.inSlot)
                table.insert(data,j)
            end
        end
    end
    for k,v in pairs(UD:getItems()) do
        if tonumber(v.itemBagType)==Enums.ItemBagType.equip then
            if v.jewelSlots then
                for k1,v1 in pairs(v.jewelSlots) do
                    if v1.jewel then
                        local j=clone(v1.jewel)
                        j:setEquipTid(v.tid)
                        j:setEquipUid(v.uid)
                        j:setOrderLevel(2)
                        j:setState(Enums.JewelState.inSlot)
                        table.insert(data,j)
                    end
                end
            end
            if v.lockedJewelSlot and v.lockedJewelSlot.jewel then
                if v.lockedJewelSlot.jewel then
                    local j=clone(v.lockedJewelSlot.jewel)
                    j:setEquipTid(v.tid)
                    j:setEquipUid(v.uid)
                    j:setOrderLevel(2)
                    j:setState(Enums.JewelState.inSlot)
                    table.insert(data,j)
                end
            end
        end
    end
    -- dump(data,"getJewelUpgradeBag data props",8)
    local function sorttable( a, b )
        if a:getOrderLevel() == b:getOrderLevel() then
            if tonumber( a:getQuality() ) == tonumber( b:getQuality() ) then
                if a:getLevel() == b:getLevel() then
                    return a.tid > b.tid
                else
                    return a:getLevel() > b:getLevel()
                end
            else
                return tonumber( a:getQuality() ) > tonumber( b:getQuality() )
            end
        else
            return a:getOrderLevel() < b:getOrderLevel()
        end
    end
    table.sort(data, sorttable)
	return data
end

--不能合成不能用的
function ClassRef:targetJewelLvCanCompose(l)
    if not self.composeNeedLevel then
        local ostr = GD:getSystemStrPar("jewelNeedLv")
        local arrOrder = string.split(ostr, "|")
        self.composeNeedLevel = {}
        for i, v in ipairs(arrOrder) do
            self.composeNeedLevel[i] = checknumber(v)
        end
    end

    if l > #self.composeNeedLevel then
        l = #self.composeNeedLevel
    end
    return UD:getPlayer().level >= checknumber(self.composeNeedLevel[l]), checknumber(self.composeNeedLevel[l])
end

function ClassRef:mapEquipLocation(lid)
    if not self.hEquipLocations then
        self.hEquipLocations = {}
        local ostr = GD:getSystemStrPar("jewelLeftEquipOrder")

        local arrOrder = string.split(ostr, "|")
        for i, v in ipairs(arrOrder) do
            self.hEquipLocations[checknumber(v)] = i
        end
    end

    return checknumber(self.hEquipLocations[lid])
end

function ClassRef:getEquipList()
    local equips = {}
    for k,v in pairs(UD.equips) do
        if v:canSetJewel() then
            equips[#equips + 1] = v
        end
    end

    local items = {}
    for k,v in pairs(UD:getItems()) do
        if v.itemBagType == Enums.ItemBagType.equip and v:canSetJewel() then
            items[#items + 1] = v
        end
    end

    -- 品质（降）》位置（升）》使用等级（降）》tid（升）
    -- local function sortEquip(a, b)
    --     if a.quality == b.quality then
    --         if self:mapEquipLocation(a.location) == self:mapEquipLocation(b.location) then
    --             if a.useLv == b.useLv then
    --                 return a.tid < b.tid
    --             else
    --                 return a.useLv > b.useLv
    --             end
    --         else
    --             return self:mapEquipLocation(a.location) < self:mapEquipLocation(b.location)
    --         end
    --     else
    --         return a.quality > b.quality
    --     end
    -- end
    local function sortEquip(a, b)
        if self:mapEquipLocation(a.location) ~= self:mapEquipLocation(b.location) then
            return self:mapEquipLocation(a.location) < self:mapEquipLocation(b.location)
        elseif a.quality ~= b.quality then
            return a.quality > b.quality
        elseif a.useLv ~= b.useLv then
            return a.useLv > b.useLv
        else
            return a.tid < b.tid
        end
    end
    table.sort(equips, sortEquip)
    table.sort(items, sortEquip)
    equips = table.attach(equips, items)
    return equips
end

function ClassRef:getEquipData(euid)
    for k,v in pairs(UD.equips) do
        if v.uid == euid then
            return v
        end
    end

    for k,v in pairs(UD:getItems()) do
        if v.uid == euid then
            return v
        end
    end
end

function ClassRef:slotHasRedPoint(euid, sidx)
    if not self.equipRedPoints then
        self:refreshRedPoint()
    end
    local e = self.equipRedPoints[euid]
    if e then
        return e[sidx]
    end
end

function ClassRef:hasRedPoint()
    if not self.equipRedPoints then
        self:refreshRedPoint()
    end
    return checknumber(self.redPointCount) > 0
end

function ClassRef:refreshRedPoint()
    local attrMap = {}
    for _,v in pairs(UD:getJewels()) do
        local m = attrMap[tostring( v:getAttrType() )]
        if not m then
            m = {}
            attrMap[tostring( v:getAttrType() )] = m
        end

        if v:getUseLv() <= UD:getLevel() then
            table.insert(m, {jewel = v, score = v:getGearScore()})
        end
    end

    for k, v in pairs(attrMap) do
        table.sort(v, function(a, b)
            return a.score > b.score
        end)
    end


    self.equipRedPoints = {}
    self.redPointCount = 0
    local function calcRedPoints(equips)
        for k,v in pairs(equips) do
            self.equipRedPoints[v.uid] = {}
            if tonumber(v.itemBagType)==Enums.ItemBagType.equip and v.jewelSlots then
                for k1,v1 in pairs(v.jewelSlots) do
                    local curScore = 0
                    if v1.slotType and v1.slotType ~= "" and v1.slotTypeList then
                        local maxScore = 0
                        for k, v in pairs(v1.slotTypeList) do
                            if v1.jewel == nil or (v1.jewel and checknumber(v1.jewel:getAttrType()) == checknumber(v) ) then --有宝石
                                local a = attrMap[tostring(v)]
                                if a and #a > 0 then
                                    if maxScore < a[1].score then
                                        maxScore = a[1].score
                                    end
                                end
                            end
                        end
                        if v1.jewel then
                            curScore = v1.jewel:getGearScore()
                        end
    
                        if curScore < maxScore then
                            self.equipRedPoints[v.uid][k1] = true
                            self.redPointCount = self.redPointCount + 1
                        end
                    end
                end
            end
        end
    end

    calcRedPoints(UD.equips)
    -- calcRedPoints(UD:getItems())

    app:sendMsg("JewelController", "updateRedPoint")
    UD.badge:setNum(Constant.FUNC_TYPE_JEWEL, self.redPointCount)
end

function ClassRef:removeItemNewFlag(uid)
    print("to removeItemNewFlag:"..uid)
    for _,v in pairs(UD:getJewels()) do
        if v.uid==uid then
            print("removeItemNewFlag:"..uid)
            v:setIsNewGet(false)
            return
        end
    end
end

--升级宝石
function ClassRef:C2S_UpgradeJewel(jewelList, jdatas)
    -- dump(costJewels,":"..jewelUid.." "..(equipUid or 0).." "..costJewelChip)
--    dump(jewelList, "jewels:", 6)
    local isInlayed = false
    for i, v in ipairs(jdatas) do
        if v:getOrderLevel() ~= 3 then
            isInlayed = true
        end
    end

    local function doRequest(jl)
        local oldJewels = self:getAllJewels()
        app.session:request("action.C2S_JewelCompose",{jewelUUID = jl},function(msg)
            self:refreshRedPoint()
            app:popMessage("jewelelevelupsuccess")
            local newJewels = self:getAllJewels()
            local function findjewel(a, t)
                for i, v in ipairs(a) do
                    if v.uid == t.uid then
                        return true
                    end
                end
                return false
            end
            local newjewel = nil
            for i, v in ipairs(newJewels) do
                if findjewel(oldJewels, v) == false then
                    newjewel = v 
                end
            end
            EM:notify("EVENT_REFRESH_UPGRADE_MODEL", newjewel)
        end, {block = true,})
    end

    if not isInlayed then
		return doRequest(jewelList)
	end

	local confirmDialog = display.newConfirmDialog(L("jewel_compose_already_inlaytips"),
			function()
				doRequest(jewelList)
			end,
			function()
			end)

	confirmDialog:setConfirmText(L("tips_ok"))
	confirmDialog:setCancelText(L("tips_cancel"))
    UIHandler:addPopDialog(confirmDialog, 1, true)    
end

--出售宝石
function ClassRef:C2S_SellJewel(uid)
    app.session:request("action.C2S_SellJewel",{uid = uid},function(msg)
        self:refreshRedPoint()
        app:popMessage("sellsuccess")
        EM:notify("EVENT_REFRESH_BAG")
    end)
end


--装备宝石
function ClassRef:C2S_InsertJewel(equipUid,slotIndex,jewelUid)
    print("ClassRef:C2S_InsertJewel equipUid:"..equipUid.." slotIndex:"..slotIndex.." jewelUid:"..jewelUid)
    app.session:request("action.C2S_InsertJewel",{equipUid = equipUid,slotType = 0,slotIndex = slotIndex,jewelUid = jewelUid},function(msg)
        self:refreshRedPoint()
        app:popMessage("jewelequipsuccess")
        EM:notify("EVENT_SETJEWEL_SUCCESS_MODEL")
        
        local data 
        local edata = self:getEquipData(equipUid)
        for k,v in pairs(edata:getAllSlots()) do
            if not v.jewel then
                data = {}
                data.euid = equipUid
                data.sidx = k
                break
            end
        end
        EM:notify("EVENT_REFRESH_BAG", data)
    end)
end

--卸下宝石
function ClassRef:C2S_RemoveJewel(equipUid,slotIndex)
    app.session:request("action.C2S_RemoveJewel",{equipUid = equipUid,slotType = 0,slotIndex = slotIndex },function(msg)
        self:refreshRedPoint()
        EM:notify("EVENT_REFRESH_BAG")        
    end,{block = true})
end
------------------------ receive ------------------------


------------------------ request ------------------------
-- 宝石炼金
function ClassRef:C2S_JewelTransInfo(sourceJewel, targetJewel)
    local params = {}
    params.jewelID = sourceJewel:getId()
    params.jewelUUID = sourceJewel:getUid()
    params.targetID = targetJewel:getId()
    -- dump(params, "C2S_JewelTransInfo params")
    app.session:request("action.C2S_JewelTransInfo", params, function(msg)
        -- dump(msg, "C2S_JewelTransInfo")
        if msg.ok then
            display.pushToast(L("RecastJewelSuccess"))
            app:sendMsg("JewelController", "refreshTransformPanel")
        end
    end)
end

return ClassRef
